package com.chunfen.dubbo.framework;

import com.chunfen.dubbo.protocol.http.HttpClient;
import com.chunfen.dubbo.register.RemoteRegister;
import com.chunfen.dubbo.util.GsonTool;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

public class ProxyFactory {

    public static <T> T getProxy(final Class interfaceClass){
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


                HttpClient httpClient = new HttpClient();
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);

                // 此时 服务地址 和端口号还是 固定的
//                Map<String, ? extends Serializable> result = httpClient.post("localhost", 8080, invocation);

                // 通过远程注册 中心获取 地址和端口号
                // 此时  RemoteRegister  在两个进程是 隔离的 所以会有空指针异常
                URL url = RemoteRegister.random(interfaceClass.getName());
                Map<String, ? extends Serializable> result = httpClient.post(url.getHostName(), url.getPort(), invocation);

                return result;
            }
        });
    }
}
